<template>
  <view class="container">
    <!-- 邀请卡片 -->
    <view class="invite-card">
      <view class="card-content">
        <view class="main-title">邀请好友成为陪伴师</view>
        <view class="divider"></view>
        
        <view class="plan-title">
          <text>陪伴师招募计划</text>
          <text class="star-icon">✨</text>
        </view>
        
        <view class="info-item">
          <text class="label">日期：</text>
          <text class="value">{{inviteInfo.startDate}} – {{inviteInfo.endDate}}</text>
        </view>
        
        <view class="info-item">
          <text class="label">时间：</text>
          <text class="value">{{inviteInfo.weekday}} {{inviteInfo.time}}</text>
        </view>
        
        <view class="info-item">
          <text class="label">平台：</text>
          <text class="value">{{inviteInfo.platform}}</text>
        </view>
        
        <view class="info-item description">
          <text class="label">活动简介：</text>
          <text class="value">{{inviteInfo.description}}</text>
        </view>
        
        <view class="info-item description">
          <text class="label">招募说明：</text>
          <text class="value">{{inviteInfo.recruitment}}</text>
        </view>
        
        <!-- 带凹槽的分割线 -->
        <view class="coupon-divider">
          <view class="left-notch"></view>
          <view class="divider-line"></view>
          <view class="right-notch"></view>
        </view>
        
        <!-- 二维码区域 -->
        <view class="qrcode-section">
          <view class="qrcode-container">
            <image :src="qrCodeUrl" class="qrcode-img"></image>
          </view>
        </view>
        
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="action-buttons">
      <view class="action-item" @click="saveImage">
        <view class="icon-wrapper download">
					<image src="/static/invite/save.png" mode="aspectFit"></image>
        </view>
        <text class="action-text">保存海报</text>
      </view>
      
      <view v-if="false" class="action-item" @click="shareToWechat">
        <view class="icon-wrapper wechat">
					<image src="/static/invite/weixin.png" mode="aspectFit"></image>
        </view>
        <text class="action-text">微信好友</text>
      </view>

      <view class="action-item" @click="shareToWechat">
        <button class="icon-wrapper wechat" open-type="share">
					<image src="/static/invite/weixin.png" mode="aspectFit"></image>
        </button>
        <text class="action-text">微信好友</text>
      </view>

      <view class="action-item" @click="shareToMoments">
        <button class="icon-wrapper moments" open-type="shareTimeline">
					<image src="/static/invite/pyq.png" mode="aspectFit"></image>
        </button>
        <text class="action-text">朋友圈</text>
      </view>
      
      <view class="action-item" @click="copyLink">
        <view class="icon-wrapper link">
					<image src="/static/invite/link.png" mode="aspectFit"></image>
        </view>
        <text class="action-text">复制链接</text>
      </view>
    </view>
    <PosterOption
			v-if="isStart"
			:isStart="isStart"
			@success="isStart = false"
			@close="isStart = false"
		></PosterOption>
    <!-- <canvas canvas-id="posterCanvas" id="posterCanvas" style="width: 750px; height: 1334px; position: fixed; top: -9999px; left: -9999px;"></canvas> -->
  </view>
</template>

<script>
import PosterOption from './PosterOption.vue'
import { getPosterInfo, joinApi,getPosterList, createPoster, posterDetailApi } from '@/api/poster'

export default {
  components: {
    PosterOption
  },
  data() {
    return {
      isStart: false,
      // isStart: true,
      inviteInfo: {
        startDate: '2025年05月04日',
        endDate: '2025年05月25日',
        weekday: '周二',
        time: '14:00 ~ 16:00',
        platform: '童行家门口小程序',
        description: '陪伴师招募活动旨在为有志于陪伴孩子成长的人士提供一份有收益的兼职机会。成为陪伴师，您将获得灵活的工作时间和丰厚的报酬。',
        recruitment: '童行家门口正在寻找充满爱心和责任感的陪伴师，成为童行家门口陪伴师，灵活工作，陪门口孩子成长，赚取丰厚收益'
      },
      qrCodeUrl: '/static/invite/default-qrcode.png', // 直接使用静态二维码图片
      shareLink: 'https://example.com/invite/12345',
      posterPath: '' // 保存生成的海报路径
    }
  },
  async onLoad() {
    // this.getPoster()
    const res = await createPoster({
      // type: 6,
      type: 1,
      jump_url: '/pages/login/login'
    })
    console.log('res==',res)
    
    // const detail = await posterDetailApi({
    //   record_id: res.record_id,
    // })
  },
  methods: {
    async getPoster() {
      const res = await getPosterInfo({
        type: 2,
        jump_url: '/pages/activity/release'
      })
      console.log('获取互动详情')
    },
    onShareTimeline() {
      return {
        title: '活动',
        // query: 'from=timeline',
        // imageUrl: this.imageUrl
      }
    },
    goBack() {
      uni.navigateBack();
    },
    downLoadCard() {
      this.isStart = !this.isStart
    },
    // 生成海报
    async generatePoster() {
      return new Promise((resolve, reject) => {
        // #ifdef APP-PLUS
        uni.createSelectorQuery()
          .select('#posterCanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node
            const ctx = canvas.getContext('2d')

            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr
            canvas.height = res[0].height * dpr
            ctx.scale(dpr, dpr)
        
            // 绘制背景
            ctx.fillStyle = '#4CAF50';
            ctx.fillRect(0, 0, 750, 1334);
            
            // 绘制卡片背景 - 增加圆角
            ctx.fillStyle = '#FFFFFF';
            this.drawRoundedRect(ctx, 75, 200, 600, 900, 30);
            
            // 绘制标题
            ctx.fillStyle = '#4CAF50';
            ctx.font = 'bold 40px sans-serif';
            ctx.fillText('邀请好友成为陪伴师', 150, 300);
            
            // 绘制分割线
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(150, 330);
            ctx.lineTo(550, 330);
            ctx.stroke();
            
            // 绘制内容
            ctx.fillStyle = '#333333';
            ctx.font = '28px sans-serif';
            ctx.fillText(`日期：${this.inviteInfo.startDate} – ${this.inviteInfo.endDate}`, 150, 400);
            ctx.fillText(`时间：${this.inviteInfo.weekday} ${this.inviteInfo.time}`, 150, 450);
            ctx.fillText(`平台：${this.inviteInfo.platform}`, 150, 500);
            
            // 绘制带凹槽的分割线
            ctx.strokeStyle = '#E0E0E0';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(150, 700);
            ctx.lineTo(550, 700);
            ctx.stroke();
            
            // 绘制二维码（靠左）
            const qrImage = canvas.createImage();
            qrImage.src = this.qrCodeUrl;
            qrImage.onload = () => {
              ctx.drawImage(qrImage, 150, 750, 180, 180);
              
              // 绘制二维码旁边的文字
              ctx.fillStyle = '#333333';
              ctx.font = 'bold 32px sans-serif';
              ctx.fillText('扫码加入', 350, 800);
              
              ctx.font = '24px sans-serif';
              ctx.fillText('成为陪伴师，获得灵活', 350, 850);
              ctx.fillText('工作时间和丰厚报酬', 350, 880);
              
              // 完成绘制
              uni.canvasToTempFilePath({
                canvas: canvas,
                destWidth: 750,
                destHeight: 1334,
                success: (res) => {
                  this.posterPath = res.tempFilePath;
                  resolve(res.tempFilePath);
                },
                fail: (err) => {
                  console.error('生成海报失败', err);
                  reject(err);
                }
              }, this);
            };
          });
        // #endif
        
        // #ifdef MP-WEIXIN
        // 微信小程序使用微信的接口生成海报
        uni.createSelectorQuery()
          .select('#posterCanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            
            const dpr = wx.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr
            canvas.height = res[0].height * dpr
            ctx.scale(dpr, dpr)
            
            // 设置画布大小
            canvas.width = 750;
            canvas.height = 1334;
            
            // 绘制背景
            ctx.fillStyle = '#4CAF50';
            ctx.fillRect(0, 0, 750, 1334);
            
            // 绘制卡片背景 - 增加圆角
            ctx.fillStyle = '#FFFFFF';
            this.drawRoundedRect(ctx, 75, 200, 600, 900, 30);
            
            // 绘制标题
            ctx.fillStyle = '#4CAF50';
            ctx.font = 'bold 40px sans-serif';
            ctx.fillText('邀请好友成为陪伴师', 150, 300);
            
            // 绘制分割线
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(150, 330);
            ctx.lineTo(550, 330);
            ctx.stroke();
            
            // 绘制内容
            ctx.fillStyle = '#333333';
            ctx.font = '28px sans-serif';
            ctx.fillText(`日期：${this.inviteInfo.startDate} – ${this.inviteInfo.endDate}`, 150, 400);
            ctx.fillText(`时间：${this.inviteInfo.weekday} ${this.inviteInfo.time}`, 150, 450);
            ctx.fillText(`平台：${this.inviteInfo.platform}`, 150, 500);
            
            // 绘制带凹槽的分割线
            ctx.strokeStyle = '#E0E0E0';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(150, 700);
            ctx.lineTo(550, 700);
            ctx.stroke();
            
            // 绘制二维码（靠左）
            const qrImage = canvas.createImage();
            qrImage.src = this.qrCodeUrl;
            qrImage.onload = () => {
              ctx.drawImage(qrImage, 150, 750, 180, 180);
              
              // 绘制二维码旁边的文字
              ctx.fillStyle = '#333333';
              ctx.font = 'bold 32px sans-serif';
              ctx.fillText('扫码加入', 350, 800);
              
              ctx.font = '24px sans-serif';
              ctx.fillText('成为陪伴师，获得灵活', 350, 850);
              ctx.fillText('工作时间和丰厚报酬', 350, 880);
              
              // 完成绘制
              wx.canvasToTempFilePath({
                canvas: canvas,
                destWidth: 750,
                destHeight: 1334,
                success: (res) => {
                  this.posterPath = res.tempFilePath;
                  resolve(res.tempFilePath);
                },
                fail: (err) => {
                  console.error('生成海报失败', err);
                  reject(err);
                }
              }, this);
            };
          });
        // #endif
      });
    },
    
    // 绘制圆角矩形
    drawRoundedRect(ctx, x, y, width, height, radius) {
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.arcTo(x + width, y, x + width, y + radius, radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
      ctx.lineTo(x + radius, y + height);
      ctx.arcTo(x, y + height, x, y + height - radius, radius);
      ctx.lineTo(x, y + radius);
      ctx.arcTo(x, y, x + radius, y, radius);
      ctx.closePath();
      ctx.fill();
    },
    
    // 保存海报到相册
    async saveImage() {
      this.isStart = true
      return
      // uni.showLoading({
      //   title: '生成海报中...'
      // });
      
      try {
        console.log("海报===", this.posterPath)
        // 如果没有生成过海报，先生成
        if (!this.posterPath) {
          this.posterPath = await this.generatePoster();
        }
        
        // 保存到相册
        uni.saveImageToPhotosAlbum({
          filePath: this.posterPath,
          success: () => {
            uni.hideLoading();
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('保存失败', err);
            
            // 如果是因为用户拒绝授权导致的失败
            if (err.errMsg.indexOf('auth deny') >= 0) {
              uni.showModal({
                title: '提示',
                content: '需要您授权保存图片到相册',
                confirmText: '去授权',
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                }
              });
            } else {
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              });
            }
          }
        });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '生成海报失败',
          icon: 'none'
        });
      }
    },
    
    // 分享给微信好友
    shareToWechat() {
      // #ifdef MP-WEIXIN
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage'],
        complete: (res) => {
          console.log('分享好友===', res)
        }
      });
      // #endif
      
      // #ifdef APP-PLUS
      // 使用原生分享
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession', // WXSceneSession = 好友, WXSceneTimeline = 朋友圈
        type: 0, // 0 = 图文, 1 = 纯文字, 2 = 纯图片, 3 = 音乐, 4 = 视频, 5 = 小程序
        title: '邀请好友成为陪伴师',
        summary: '成为陪伴师，获得灵活的工作时间和丰厚的报酬',
        imageUrl: this.posterPath || '/static/images/share-default.png',
        href: this.shareLink,
        success: (res) => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('分享失败', err);
          uni.showToast({
            title: '分享失败',
            icon: 'none'
          });
        }
      });
      // #endif
    },
    
    // 分享到朋友圈
    shareToMoments() {
      // #ifdef APP-PLUS
      // 使用原生分享
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneTimeline', // WXSceneSession = 好友, WXSceneSession = 朋友圈
        type: 0,
        title: '邀请好友成为陪伴师',
        summary: '成为陪伴师，获得灵活的工作时间和丰厚的报酬',
        imageUrl: this.posterPath || '/static/images/share-default.png',
        href: this.shareLink,
        success: (res) => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('分享失败', err);
          uni.showToast({
            title: '分享失败',
            icon: 'none'
          });
        }
      });
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序不支持直接分享到朋友圈，可以引导用户保存图片后手动分享
      uni.showModal({
        title: '提示',
        content: '小程序暂不支持直接分享到朋友圈，请点击有上角 ... 打开菜单进行分享操作！',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
          }
        }
      });
      // #endif
    },
    
    // 复制链接
    copyLink() {
      uni.setClipboardData({
        data: this.shareLink,
        success: () => {
          uni.showToast({
            title: '链接已复制',
            icon: 'success'
          });
        }
      });
    }
  },
  // 小程序分享设置
  onShareAppMessage() {
    return {
      title: '邀请好友成为陪伴师',
      path: '/pages/teacher_manage/index?id=12345',
      imageUrl: this.posterPath || '/static/images/share-default.png'
    };
  },
  // 分享到朋友圈（仅支持部分新版微信）
  onShareTimeline() {
    return {
      title: '邀请好友成为陪伴师',
      query: 'id=12345',
      imageUrl: this.posterPath || '/static/images/share-default.png'
    };
  }
}
</script>

<style>
page {
  overflow: hidden;
}
.container {
  width: 100vw;
  height: 100vh;
  background-color: #4CAF50;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-sizing: border-box;
}

.invite-card {
  width: 690rpx;
  margin: 0 auto;
  border-radius: 30rpx; /* 优化容器圆角 */
  overflow: hidden;
  background-color: #fff;
  position: relative;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15); /* 增强阴影效果 */
}

.card-content {
  padding: 40rpx 40rpx 20rpx;
  position: relative;
}

.main-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 20rpx;
  text-align: center;
}

.divider {
  height: 2rpx;
  background-color: #E0E0E0;
  margin: 20rpx 0 30rpx;
}

.plan-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 26rpx;
  display: flex;
  align-items: center;
}

.star-icon {
  margin-left: 10rpx;
  font-size: 40rpx;
}

.info-item {
  margin-bottom: 16rpx;
  font-size: 30rpx;
  line-height: 1.5;
}

.label {
  color: #757575;
  font-weight: 500;
}

.value {
  color: #333;
}

.description {
  display: flex;
  flex-direction: column;
}

.description .label {
  margin-bottom: 10rpx;
}

.description .value {
  line-height: 1.6;
}

/* 带凹槽的分割线 */
.coupon-divider {
  position: relative;
  height: 40rpx;
  margin: 20rpx -40rpx;
  display: flex;
  align-items: center;
}

.divider-line {
  flex: 1;
  height: 2rpx;
  border-top: 1px dashed #E0E0E0 ;
}

.left-notch, .right-notch {
  width: 30rpx;
  height: 30rpx;
  border-radius: 50%;
  background-color: #4CAF50;
  position: relative;
  z-index: 1;
}

.left-notch {
  margin-right: -15rpx;
  transform: translateX(-50%);
}

.right-notch {
  margin-left: -15rpx;
  transform: translateX(50%);
}

/* 二维码区域 */
.qrcode-section {
  display: flex;
  align-items: center;
  padding: 0 0;
}

.qrcode-container {
  flex-shrink: 0;
  margin-right: 30rpx;
}

.qrcode-img {
  width: 180rpx;
  height: 180rpx;
  border: 1rpx solid #E0E0E0;
  border-radius: 10rpx;
}

.qrcode-text {
  flex: 1;
}

.scan-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.scan-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.action-buttons {
  width: 100vw;
  height: 140rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 30rpx;
  background-color: #4CAF50;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.action-item image {
	width: 100%;
	height: 100%;
}

.icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
	margin-bottom: 10rpx;
}

.icon-wrapper .iconfont {
  font-size: 40rpx;
}

.download .iconfont {
  color: #FF9800;
}

.wechat .iconfont {
  color: #4CAF50;
}

.moments .iconfont {
  color: #2196F3;
}

.link .iconfont {
  color: #9C27B0;
}

.action-text {
  font-size: 24rpx;
  color: #fff;
}

/* 隐藏的canvas用于生成海报 */
#posterCanvas {
  position: fixed;
  left: -9999rpx;
  width: 100vw;
  height: 1334rpx;
}
</style>